<?php

namespace App\models;
use App\models\rbac\AdminRole;
use App\models\rbac\ResourceUri;
use App\models\rbac\RoleResource;
use App\traits\RbacTrait;
use App\traits\ValidateTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

/**
* This is the model class for table "admin".
*
* @property integer $id 
* @property string $name 
* @property string $telephone 
* @property string $email 
* @property string $password 
* @property string $remember_token 
* @property string $created_at 
* @property string $updated_at 
*/


class Admin extends Authenticatable
{

    use Notifiable , ValidateTrait ,RbacTrait;

    protected $table = 'admin';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'telephone'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    public function roles(){
        return $this->hasMany(AdminRole::class , 'admin_id', 'id') ;
    }

    public function CheckRule($path,$method){

        $roleIds = $this->roles->pluck('role_id')->toArray() ;
        if(empty($roleIds)){
            return false ;
        }

        $resIds = RoleResource::whereIn('role_id',$roleIds)->pluck('resource_id')->toArray() ;
        if(empty($resIds)){ return false ; }

        $resIds = array_unique($resIds) ;
        $rules = ResourceUri::select('uri','method')->whereIn('resource_id',$resIds)->get()->toArray() ;

        if (empty($rules)){
            return false ;
        } 
        return $this->mathRules($path, $method,$rules );
    }

    public static function saveRoles($roleIds , $adminId){
        // 删除关系
        AdminRole::where('admin_id',$adminId)->delete();
        $data = [] ;
        foreach ($roleIds as $rid){
            $data[] = ['admin_id' => $adminId , 'role_id' => $rid ] ;
        }

        return AdminRole::insert($data) ;
    }

    
}
